﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.SessionState;
using Castle.Windsor;
using CommonServiceLocator.WindsorAdapter;
using HibernatingRhinos.Profiler.Appender.NHibernate;
using log4net.Config;
using Microsoft.Practices.ServiceLocation;
using MvcMall.AdminWeb.CastleWindsor;
using MvcMall.Data.NHibernateMaps;
using MvcMall.Framework.Extensions;
using SharpArch.Data.NHibernate;
using SharpArch.Web.Castle;
using SharpArch.Web.NHibernate;

namespace MvcMall.AdminWeb
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // 在应用程序启动时运行的代码
            NHibernateProfiler.Initialize();
            XmlConfigurator.Configure();
            InitializeServiceLocator();
        }

        void Application_End(object sender, EventArgs e)
        {
            //  在应用程序关闭时运行的代码

        }

        void Application_Error(object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行的代码

        }

        void Session_Start(object sender, EventArgs e)
        {
            // 在新会话启动时运行的代码

        }

        void Session_End(object sender, EventArgs e)
        {
            // 在会话结束时运行的代码。 
            // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
            // InProc 时，才会引发 Session_End 事件。如果会话模式设置为 StateServer 
            // 或 SQLServer，则不会引发该事件。

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            // Only initialise the NHibernate Sessions for a non static, i.e. Controller Action request
            if (!Request.IsStaticFile())
            {
                NHibernateInitializer.Instance().InitializeNHibernateOnce(InitializeNHibernateSession);
            }
        }

        private WebSessionStorage _webSessionStorage;
        public override void Init()
        {
            base.Init();

            // The WebSessionStorage must be created during the Init() to tie in HttpApplication events
            _webSessionStorage = new WebSessionStorage(this);
        }


        protected void InitializeServiceLocator()
        {
            IWindsorContainer container = new WindsorContainer();
            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
            ComponentRegistrar.AddComponentsTo(container);
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
        }

        private void InitializeNHibernateSession()
        {
            NHibernateSession.Init(
                _webSessionStorage,
                new[] { Server.MapPath("~/bin/MvcMall.Data.dll") },
                new AutoPersistenceModelGenerator().Generate(),
                Server.MapPath("~/NHibernate.config"));
        }

    }
}
